#define  _CRT_SECURE_NO_WARNINGS 1
#include "seqlist.h"


void seqlist_init(SL* ps)
{
	ps->a = NULL;
	ps->size = 0;
	ps->capacity = 0;

	//memset(ps->a, 0, MAX_SIZE * sizeof(SL_TYPE));
	//ps->size = 0;
}

void print(SL* ps)
{
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}

void seqlist_destory(SL* ps)
{
	free(ps->a);
	ps->a = NULL;
	ps->capacity = 0;
	ps->size = 0;
}


static void seqlist_checkcapacity(SL* ps)
{
	if (ps->size == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 5 : ps->capacity * 2;
		SL_TYPE* pn = (SL_TYPE*)realloc(ps->a, sizeof(SL_TYPE) * newcapacity);
		if (pn != NULL)
		{
			ps->a = pn;
			ps->capacity = newcapacity;
		}
		else
		{
			perror("realloc");
			return;
		}
	}
}

void seqlist_pushback(SL* ps, SL_TYPE x)
{
	/*if (ps->size == MAX_SIZE)
	{
		printf("seqlist is full\n");
		return;
	}
	ps->a[ps->size] = x;
	ps->size++;*/
	seqlist_checkcapacity(ps);
	ps->a[ps->size] = x;
	ps->size++;
}

void seqlist_pushfront(SL* ps, SL_TYPE x)
{
	seqlist_checkcapacity(ps);
	//memmove(ps->a + 1, ps->a, ps->size * sizeof(SL_TYPE));
	int end = ps->size - 1;
	while (end >= 0)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[0] = x;
	ps->size++;
}

void seqlist_popback(SL* ps)
{
	assert(ps->size > 0);

	ps->size--;

}

void seqlist_popfront(SL* ps)
{
	assert(ps->size > 0);

	//memmove(ps->a, ps->a + 1, (ps->size - 1) * sizeof(SL_TYPE));
	for (int i = 1; i < ps->size; i++)
	{
		ps->a[i - 1] = ps->a[i];
	}
	ps->size--;
}

void seqlist_insert(SL* ps, int pos, SL_TYPE x)
{
	assert(pos < ps->size);
	seqlist_checkcapacity(ps);
	int end = ps->size - 1;
	while (end >= pos)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[pos] = x;
	ps->size++;
}

void seqlist_erase(SL* ps, int pos)
{
	assert(pos < ps->size);
	int end = ps->size - 1;
	while (pos < end)
	{
		ps->a[pos] = ps->a[pos + 1];
		pos++;
	}
	ps->size--;
}



int seqlist_find(SL* ps, SL_TYPE x)
{
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->a[i] == x)
			return i;
	}
	return -1;
}


void seqlist_modity(SL* ps, int pos, SL_TYPE x)
{
	assert(pos < ps->size);
	ps->a[pos] = x;

}
